package class04;

import java.util.Arrays;

/**
 * <a href="https://leetcode.cn/problems/reverse-pairs/">493. 翻转对</a>
 */
public class Code04_BiggerThanRightTwice {
    public static int way1(int[] arr) {
        return process(arr, 0, arr.length - 1);
    }

    private static int process(int[] arr, int L, int R) {
        if (L == R) {
            return 0;
        }
        int M = L + ((R - L) >> 1);
        return process(arr, L, M) + process(arr, M + 1, R) + merge(arr, L, M, R);
    }

    private static int merge(int[] arr, int L, int M, int R) {
        int[] help = new int[R - L + 1];
        int index = 0;
        int result = 0;
        int l = L;
        int r = M + 1;
        for (; l <= M; ++l) {
            while (r <= R && (long) arr[l] > ((long) arr[r] << 1)) {
                r++;
            }
            result += r - (M + 1);
        }
        l = L;
        r = M + 1;
        while (l <= M || r <= R) {
            if (l > M) {
                help[index++] = arr[r++];
            } else if (r > R) {
                help[index++] = arr[l++];
            } else {
                help[index++] = arr[l] < arr[r] ? arr[l++] : arr[r++];
            }
        }
        System.arraycopy(help, 0, arr, L, help.length);
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 2, 3, 1};
        int[] arr1 = {2, 4, 3, 5, 1};
        System.out.println(way1(arr));
        System.out.println(way1(arr1));
        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(arr1));
    }
}
